package cn.edu.gdgm.system.utils;


import cn.edu.gdgm.system.entity.Plan;
import cn.edu.gdgm.system.job.PublishJob;
import org.quartz.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Calendar;
import java.util.Date;

/**
 * @author quan
 * @date 2021-02-27
 */
@Service
public class JobUtils {
    @Resource
    private SchedulerFactoryBean schedulerFactoryBean;

    private Logger log = LoggerFactory.getLogger(getClass());

    private Class JOB_CLASS = PublishJob.class;

    /**
     * 添加定时任务
     * @param plan plan
     */
    public void addJob(Plan plan, String drugName) {
        System.out.println(plan);
        Date planTime = plan.getPlanTime();
        String invokeTarget = plan.getInvokeTarget();
        String deviceUuid = plan.getDeviceUuid();

        String baseCron = "0,5,10 %d %d * * ? ";
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(planTime);
        int hour = calendar.get(Calendar.HOUR_OF_DAY);
        int minute = calendar.get(Calendar.MINUTE);
        String cron = String.format(baseCron, minute, hour);
        log.info("解析的时间：{}", cron);
        Scheduler scheduler = schedulerFactoryBean.getScheduler();
        try {
            // 任务
            JobDetail jobDetail = JobBuilder
                    .newJob(JOB_CLASS)
                    .usingJobData("deviceUuid", deviceUuid)
                    .usingJobData("drugName", drugName)
                    .usingJobData("lampPosition", plan.getSlotId())
                    .build();
            // 触发器
            TriggerKey triggerKey = TriggerKey.triggerKey(invokeTarget, Scheduler.DEFAULT_GROUP);
            CronTrigger trigger = TriggerBuilder.newTrigger()
                    .withIdentity(triggerKey)
                    .withSchedule(CronScheduleBuilder.cronSchedule(cron)).build();
            scheduler.scheduleJob(jobDetail, trigger);
            // 启动
            if (!scheduler.isShutdown()) {
                scheduler.start();
                log.info("---任务[ {} ]启动成功-------", triggerKey.getName());
            }else{
                log.info("---任务[ {} ]已经运行，请勿再次启动-------", triggerKey.getName());
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 删除任务
     * @param invokeTarget 任务ID
     */
    public void deleteJob(String invokeTarget) {
        Scheduler scheduler = schedulerFactoryBean.getScheduler();
        TriggerKey triggerKey = TriggerKey.triggerKey(invokeTarget, Scheduler.DEFAULT_GROUP);
        try {
            if (checkJob(invokeTarget)) {
                scheduler.pauseTrigger(triggerKey);
                scheduler.unscheduleJob(triggerKey);
                scheduler.deleteJob(JobKey.jobKey(invokeTarget, Scheduler.DEFAULT_GROUP));
                log.info("---任务[ {} ]删除成功-------", triggerKey.getName());
            }
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
    }

    /**
     * 检查是否存在该任务
     * @param invokeTarget 任务ID
     * @return true存在 false不存在
     */
    public boolean checkJob(String invokeTarget){
        Scheduler scheduler = schedulerFactoryBean.getScheduler();
        TriggerKey triggerKey = TriggerKey.triggerKey(invokeTarget, Scheduler.DEFAULT_GROUP);
        try {
            if(scheduler.checkExists(triggerKey)){
                return true;
            }
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
        return false;
    }
}
